<template>
	<div class="app-container">
		<el-form class="queryForms" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="客户名称" prop="clientName">
				<el-input v-model="queryParams.clientName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="客户状态" prop="clientState">
				<el-select v-model="queryParams.clientState" placeholder="客户状态" clearable>
					<el-option v-for="dict in dict.type.default_status" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['erp:client:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['erp:client:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['erp:client:report']">导入</el-button>
			</el-col>
			<right-toolbar menuNames="custom63" @changeTableData="changeTableData" :showSearch.sync="showSearch" @queryTable="getList" :columns.sync="columns" perm="erp:client:list"></right-toolbar>
		</el-row>

		<div :class="eleTabTop <= 85 ? 'eleTab' : ''" class="informationTab" ref="eleTab">
			<el-table @row-click="row_click" v-loading="loading" :data="clientList" @selection-change="handleSelectionChange" border height="100%" ref="table">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55" />
				<el-table-column label="客户名称" prop="clientName" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="客户代表" prop="clientType" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="联系人" prop="contacts" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="联系人电话" align="center" prop="contactsPhone" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="状态" align="center" prop="clientState" min-width="150" :show-overflow-tooltip="true" v-if="columns[4].visible">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.clientState" active-value="1" inactive-value="0" @change="handleStatusChange(scope.row)"> </el-switch>
					</template>
				</el-table-column>
				<el-table-column label="监管协议号/凭证" prop="protocolNumber" min-width="250" :show-overflow-tooltip="true" v-if="columns[5].visible">
					<template slot-scope="scope">
						<div :style="{ color: scope.row.protocolNumberState == '1' ? 'red' : '' }">{{ scope.row.protocolNumber }}</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['erp:client:edit']">修改</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['erp:client:remove']">删除</el-button>
						<el-button size="mini" type="text" icon="el-icon-s-order" @click="handleProtocol(scope.row)" v-hasPermi="['erp:client:protocol']">监管协议号管理</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination68" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改客户对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" :model="form" :rules="rules" label-width="90px">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="客户名称" prop="clientName">
							<el-input v-model="form.clientName" placeholder="请输入客户名称" maxlength="20" show-word-limit  :disabled="editFlag" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="客户代表" prop="clientType">
							<el-input v-model="form.clientType" placeholder="请输入客户代表" maxlength="20" show-word-limit  :disabled="editFlag" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="联系人" prop="contacts">
							<el-input v-model="form.contacts" placeholder="请输入联系人" maxlength="20" show-word-limit  :disabled="editFlag" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系人电话" prop="contactsPhone">
							<el-input v-model="form.contactsPhone" placeholder="请输入联系人电话" maxlength="11"  :disabled="editFlag" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="收件地址" prop="consigneeAddress">
							<el-input show-word-limit v-model="form.consigneeAddress" placeholder="请输入收件地址" maxlength="30"  :disabled="editFlag" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="客户状态" prop="clientState">
							<el-radio-group v-model="form.clientState">
								<el-radio v-for="dict in dict.type.default_status" :key="dict.value" :label="dict.value" :disabled="editFlag">{{ dict.label }}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<!-- 新增  修改  false -->
				<el-divider content-position="center" v-if="showcustomInfo">客户监管协议号信息</el-divider>
				<el-table :data="form.tclientProtocolList" :row-class-name="rowTClientProtocolIndex" ref="tClientProtocol" v-if="showcustomInfo" border>
					<el-table-column label="序号" align="center" type="index" width="55" />
					<el-table-column label="监管协议号/凭证" prop="protocolNumber" width="350" align="center">
						<template slot-scope="scope">
							<el-input v-model="scope.row.protocolNumber" placeholder="请输入监管协议号/凭证" maxlength="50"  />
						</template>
					</el-table-column>
					<el-table-column label="状态" prop="state" width="150" align="center">
						<template slot-scope="scope">
							<el-switch v-model="scope.row.state" active-value="1" inactive-value="0"> </el-switch>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
						<template slot-scope="scope">
							<el-button size="mini" type="text" icon="el-icon-plus" v-if="scope.row.showButton" @click="handleCreateds(scope.row)">创建</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" v-if="!scope.row.showButton" @click="handleDeleteNumber(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 客户导入对话框 -->
		<el-dialog :title="upload.title" :visible.sync="upload.open" width="410px" append-to-body v-dialogDrag>
			<el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip text-center" slot="tip">
					<div class="el-upload__tip" slot="tip">
						<el-checkbox v-model="upload.updateSupport" />
						是否更新已经存在的用户数据
					</div>
					<span>仅允许导入xls、xlsx格式文件。</span>
					<el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
				</div>
			</el-upload>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFileForm">确 定</el-button>
				<el-button @click="upload.open = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { listClient, getClient, delClient, addClient, updateClient } from "@/api/system/custom"
import { getToken } from "@/utils/auth"
import { getcolumn } from "@/api/selectList"
export default {
	name: "Client",
	dicts: ["default_status"],
	data() {
		return {
			eleTabTop: 0, //表格容器距浏览器顶部距离
			showcustomInfo: true,
			// 导入参数
			upload: {
				// 是否显示弹出层
				open: false,
				// 弹出层标题
				title: "",
				// 是否禁用上传
				isUploading: false,
				// 是否更新已经存在的用户数据
				updateSupport: 0,
				// 设置上传的请求头部
				headers: { Authorization: "Bearer " + getToken() },
				// 上传的地址
				url: process.env.VUE_APP_BASE_API + "/erp/client/importData"
			},
			// 基础信息是否可更改
			editFlag: false,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 客户表格数据
			clientList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				clientName: null,
				clientType: null,
				contacts: null,
				contactsPhone: null,
				clientState: null
			},
			// 表单参数   // 客户监管协议号表格数据
			form: {
				clientState: "1",
				tclientProtocolList: [{ protocolNumber: "", state: "1", showButton: true }]
			},
			// 表单校验
			rules: {
				contactsPhone: [
					{
						pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
						message: "请输入正确的手机号码",
						trigger: "blur"
					}
				],
				clientName: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
				clientType: [{ required: true, message: "客户代表不能为空", trigger: "blur" }]
			},
			// 列信息
			columns: [
				{ key: 0, label: `客户名称`, visible: true },
				{ key: 1, label: `客户代表`, visible: true },
				{ key: 3, label: `联系人`, visible: true },
				{ key: 4, label: `联系人电话`, visible: true },
				{ key: 5, label: `状态`, visible: true },
				{ key: 6, label: `监管协议号/凭证`, visible: true }
			]
		}
	},
	created() {
		this.getSize()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
    this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
    getSize() {
			getcolumn({ pageName: "Pagination67" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		/** 下载模板操作 */
		importTemplate() {
			this.download("/erp/client/importTemplate", {}, `客户模板_${new Date().getTime()}.xlsx`)
		},
		// 文件上传中处理
		handleFileUploadProgress(event, file, fileList) {
			this.upload.isUploading = true
		},
		// 文件上传成功处理
		handleFileSuccess(response, file, fileList) {
			this.upload.open = false
			this.upload.isUploading = false
			this.$refs.upload.clearFiles()
			this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
			this.getList()
		},
		// 提交上传文件
		submitFileForm() {
			this.$refs.upload.submit()
		},
		/** 导入按钮操作 */
		handleImport() {
			this.upload.title = "客户导入"
			this.upload.open = true
		},
		// 客户状态修改
		handleStatusChange(row) {
			this.$modal
				.confirm("确认要修改客户状态吗？")
				.then(function () {
					return updateClient({
						id: row.id,
						clientState: row.clientState,
						alterState: 1
					})
				})
				.then(() => {
					this.$modal.msgSuccess("修改成功")
				})
				.catch(function () {
					row.clientState = row.clientState === "0" ? "1" : "0"
				})
		},
		// 协议号删除
		handleDeleteNumber(row) {
			this.form.tclientProtocolList.splice(row.index, 1)
		},
		// 协议号创建
		handleCreateds(row) {
			if (this.form.tclientProtocolList[this.form.tclientProtocolList.length - 1].protocolNumber) {
				this.form.tclientProtocolList.push({
					protocolNumber: "",
					state: "1",
					showButton: false
				})
			} else {
				this.$modal.msgError("请先填写监管协议号")
			}
		},
		// 监管协议号
		handleProtocol(row) {
			this.editFlag = true
			this.showcustomInfo = true
			this.reset()
			const id = row.id
			this.getClientForm(id, 2)
		},
		/** 查询客户列表 */
		getList() {
			this.loading = true
			listClient(this.queryParams).then(response => {
				this.clientList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 取消按钮
		cancel() {
			this.open = false
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				clientName: null,
				clientType: null,
				contacts: null,
				contactsPhone: null,
				clientState: "1",
				remark: null,
				tclientProtocolList: [{ protocolNumber: "", state: "1", showButton: true }]
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.editFlag = false
			this.showcustomInfo = true
			this.open = true
			this.title = "添加客户"
		},
		getClientForm(id, status) {
			getClient(id).then(response => {
				this.form = response.data
				this.form.alterState = status == "1" ? "0" : "1"
				if (this.form.tclientProtocolList && this.form.tclientProtocolList.length > 0) {
					this.form.tclientProtocolList.forEach((element, index) => {
						if (index == 0) {
							this.form.tclientProtocolList[index].showButton = true
						} else {
							this.form.tclientProtocolList[index].showButton = false
						}
					})
				} else {
					this.form.tclientProtocolList = [{ protocolNumber: "", state: "1", showButton: true }]
				}
				this.open = true
				this.title = status == "1" ? "修改客户" : "设置监管协议号"
			})
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			this.editFlag = false
			this.showcustomInfo = false
			const id = row.id || this.ids
			this.getClientForm(id, 1)
		},
		/** 提交按钮 */
		submitForm() {
			let flag = this.form.tclientProtocolList.every(item => item.protocolNumber != "")
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (flag) {
						if (this.form.id != null) {
							updateClient(this.form).then(response => {
								this.$modal.msgSuccess("修改成功")
								this.open = false
								this.getList()
							})
						} else {
							addClient(this.form).then(response => {
								this.$modal.msgSuccess("新增成功")
								this.open = false
								this.getList()
							})
						}
					} else {
						this.$modal.msgError("请先填写监管协议号")
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除客户数据项？")
				.then(function () {
					return delClient(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => {})
		},
		/** 客户监管协议号序号 */
		rowTClientProtocolIndex({ row, rowIndex }) {
			row.index = rowIndex
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"erp/client/export",
				{
					...this.queryParams
				},
				`client_${new Date().getTime()}.xlsx`
			)
		}
	}
}
</script>
<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 250px !important;
}
</style>
